package com.sibbay.vta;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
import com.sibbay.tools.Parser;
import com.sibbay.tools.Tools;
import com.sibbay.vta.adaptor.StationListAdapter;
import com.sibbay.vta.adaptor.TimeListAdapter;
import com.sibbay.vta.cache.Cache;

public class RouteListActivity extends CommonActivity {
	private static final String TAG = "VTA RouteListActivity";

	static final String EXTRA_TITLE = "Title";
	static final String EXTRA_URL = "Url";
	static final String EXTRA_MAP_URL = "Map_Url";
	static final String EXTRA_DAY = "Day";

	private static final long DELAY_MILLIS = 1000;
	private final Handler mHandler = new Handler(); 
	private final Runnable mDoInTimeRefresh = new Runnable() {
		@Override
		public void run() {
	        mTimeListAdapter.setStation(mStationListAdapter.getSelected());
			mHandler.postDelayed(mDoInTimeRefresh, DELAY_MILLIS);
		}
	};

	private TimeListAdapter mTimeListAdapter;
	private StationListAdapter mStationListAdapter;
	private ListView mTimeList;
	private ListView mStationList;
	private String mUrl;
	private String mMapUrl;
	private String mTitleStr;
	private String mDayStr;
    private boolean mGotError;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.route_list);
        final ImageView fav = (ImageView) findViewById(R.id.in_favorites);
        final SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.black_star);
        fav.setImageDrawable(svg.createPictureDrawable());
        
        // set to default
		fav.setVisibility(View.INVISIBLE);
		mGotError = false;
		
        final Intent intent = getIntent();
        mUrl = intent.getStringExtra(EXTRA_URL);
        mMapUrl = intent.getStringExtra(EXTRA_MAP_URL);
        mTitleStr = intent.getStringExtra(EXTRA_TITLE);
        mDayStr = intent.getStringExtra(EXTRA_DAY);
        
        ((TextView)findViewById(R.id.title)).setText(mTitleStr);
        ((TextView)findViewById(R.id.title_day)).setText(mDayStr);

        final File file = Cache.getInstance(this).get(mUrl);
        if (file != null) {
        	Log.d(TAG, "get from cache: " + file);
        	setList(this, file);
        	return;
        }

        // file doesn't exist 
        // start downloading process 
        new Cache.DownloaderTask(this) {
			@Override
    	    protected void onFinished(final File file) {
    	        setList(RouteListActivity.this, file);
    	    }
			@Override
			protected void onError() {
				mGotError = true;
				Toast.makeText(RouteListActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
			}
        }.execute(mUrl, Cache.getInstance(this).getFileName(mUrl));
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mGotError) {
			getMenuInflater().inflate(R.menu.route, menu);
		}
	    return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (!mGotError) {
			if (Favorites.has(this, Tools.getKey(mUrl))) {
				menu.findItem(R.id.menu_add_to_favorites).setVisible(false);
				menu.findItem(R.id.menu_rm_from_favorites).setVisible(true);
			} else{
				menu.findItem(R.id.menu_add_to_favorites).setVisible(true);
				menu.findItem(R.id.menu_rm_from_favorites).setVisible(false);
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    if (item.getItemId() == R.id.menu_clean_up_cache) {
			final File file = Cache.getInstance(this).get(mUrl);
			if (file != null) {
	        	file.delete();
	        }
			return true;
		} else if (item.getItemId() == R.id.menu_add_to_favorites) {
			Favorites.add(this, Tools.getKey(mUrl), mUrl, mMapUrl, mTitleStr, mDayStr);
			findViewById(R.id.in_favorites).setVisibility(View.VISIBLE);
			return true;
		} else if (item.getItemId() == R.id.menu_rm_from_favorites) {
			Favorites.remove(this, Tools.getKey(mUrl));
			findViewById(R.id.in_favorites).setVisibility(View.INVISIBLE);
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		
		if (mStationListAdapter != null)
			saveCurrLine(this, mUrl, mStationListAdapter.getSelected());	// restore in setList
	}
	
	///
	
	private static void setList(final RouteListActivity activity, final File file) {
		final Parser parser = new Parser();
    	try {
			parser.parse(file);
			if (!parser.isValid()) {
				Log.d(TAG, "not valid: " + file);
				file.delete();
				Toast.makeText(activity, R.string.data_problem, Toast.LENGTH_LONG).show();
				return;
			}

			activity.mTimeList = (ListView) activity.findViewById(R.id.time_list);
	        activity.mTimeListAdapter = new TimeListAdapter(activity, parser.getTimeTable(), parser.getMaxTimeTabletSize());
	        activity.mTimeList.setAdapter(activity.mTimeListAdapter);

	        activity.mStationList = (ListView) activity.findViewById(R.id.station_list);
			activity.mStationListAdapter = new StationListAdapter(activity, parser.getStationList());
			activity.mStationList.setAdapter(activity.mStationListAdapter);
			activity.mStationList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> l, View v, int pos, long id) {
					activity.mStationListAdapter.setSelected(pos);
					pos = activity.mTimeListAdapter.setStation(pos);
					activity.mTimeList.smoothScrollToPosition(pos);
				}
			});

			if (Favorites.has(activity, Tools.getKey(activity.mUrl))) 
				activity.findViewById(R.id.in_favorites).setVisibility(View.VISIBLE);

			activity.mStationListAdapter.setSelected(restoreCurrLine(activity, activity.mUrl));
			activity.mStationList.smoothScrollToPosition(activity.mStationListAdapter.getSelected());
	        final int pos = activity.mTimeListAdapter.setStation(activity.mStationListAdapter.getSelected());
	        activity.mTimeList.smoothScrollToPosition(pos);
	        activity.mHandler.postDelayed(activity.mDoInTimeRefresh, DELAY_MILLIS);
    	} catch (IOException e) {
			e.printStackTrace();
			Log.d(TAG, "cannot parse: " + file);
			Toast.makeText(activity, R.string.data_conn_problem, Toast.LENGTH_LONG).show();
			return;
		}
	}
	
	///

	private static final String CURR_LINE_PREF = "curr_line";
	
	private static void saveCurrLine(final Context ctx, final String url, int line) {
		final SharedPreferences pref = ctx.getSharedPreferences(CURR_LINE_PREF, 0);
		final SharedPreferences.Editor edit = pref.edit();
		edit.putInt(Tools.getKey(url), line);
		edit.commit();
	}

	private static int restoreCurrLine(final Context ctx, final String url) {
		final SharedPreferences pref = ctx.getSharedPreferences(CURR_LINE_PREF, 0);
		return pref.getInt(Tools.getKey(url), 0);
	}
}
